<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="label">货物:</div>
      <el-input
        v-model="listQuery.name"
        placeholder="输入货物名称"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleSearch"
      />

      <div class="label">货物类型:</div>
      <el-select
        v-model="listQuery.goodsTypeId"
        class="filter-item"
        style="max-width: 200px"
        placeholder="选择类型"
      >
        <el-option
          v-for="item in searchGoodsTypeList"
          :key="item.code"
          :label="item.name"
          :value="item.code"
        />
      </el-select>

      <div class="label">操作时间:</div>
      <el-date-picker
        v-model="timeFrame"
        type="datetimerange"
        range-separator=" ~ "
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :default-time="['00:00:00', '23:59:59']"
        align="right"
        style="height: 36px"
      />
      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate"
      >新增</el-button>
      <el-button
        v-waves
        class="filter-item"
        style="margin-left: 10px"
        type="info"
        icon="el-icon-refresh"
        @click="resetSearch()"
      >重置</el-button>
      <el-button
        v-waves
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch()"
      >搜索</el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      stripe
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="sortChange"
    >
      <el-table-column label="货物编号" prop="sort" align="center" width="80">
        <template slot-scope="{ row }">
          <span>{{ row.sort }}</span>
        </template>
      </el-table-column>

      <el-table-column label="货物名称" min-width="110px">
        <template slot-scope="{ row }">
          <span class="link-type" @click="handleUpdate(row)">
            {{ row.name }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="货物类型" align="center">
        <template slot-scope="{ row }">
          <span>{{ goodsTypeName(row.goodsTypeId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="重量(吨)" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.weight }}</span>
        </template>
      </el-table-column>
      <el-table-column label="体积(m³)" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.volume }}</span>
        </template>
      </el-table-column>
      <el-table-column label="数量" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.quantity }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单位" align="center">
        <template slot-scope="{ row }">
          <span>{{ unitName(row.unitId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作人" min-width="150px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.lastUpdateUserName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作时间" min-width="150px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.lastUpdateTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button
            type="primary"
            size="mini"
            @click="handleUpdate(row)"
          >编辑</el-button>

          <el-button
            v-if="row.status != 'deleted'"
            size="mini"
            type="danger"
            @click="handleDelete(row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="80px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="货物名称" prop="name">
          <el-input v-model="temp.name" placeholder="请输入货物名称" />
        </el-form-item>
        <el-form-item label="货物类型" prop="goodsTypeId">
          <el-select
            v-model="temp.goodsTypeId"
            class="filter-item"
            style="width: 100%"
            placeholder="选择类型"
          >
            <el-option
              v-for="item in goodsTypeList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="货物重量" prop="weight">
          <div class="content">
            <el-input
              v-model="temp.weight"
              class="val"
              placeholder="请输入货物重量"
            />
            <label class="label">吨</label>
          </div>
        </el-form-item>
        <el-form-item label="货物体积">
          <div class="content">
            <el-input v-model="temp.volume" placeholder="请输入货物体积" />
            <label class="label">m³</label>
          </div>
        </el-form-item>
        <el-form-item label="数量">
          <el-input v-model="temp.quantity" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="单位">
          <el-select
            v-model="temp.unitId"
            class="filter-item"
            style="width: 100%"
            placeholder="选择单位"
          >
            <el-option
              v-for="item in unitList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="createData()">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchCargoList,
  createCargo,
  delCargo,
  getGoodsTypeList,
  getUnitList
} from '@/api/tms/cargo'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import { parseTime } from '@/utils'

export default {
  name: 'ComplexTable',
  components: {
    Pagination
  },
  directives: {
    waves
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        current: 1,
        size: 20,
        name: undefined,
        goodsTypeId: undefined,
        names: [],
        goodsTypeIds: [],
        operationStartTime: undefined,
        operationEndTime: undefined
      },
      temp: {
        id: undefined,
        goodsTypeId: '',
        name: '',
        weight: '',
        volume: undefined,
        quantity: undefined,
        unitId: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑货物',
        create: '新增货物'
      },
      pvData: [],
      rules: {
        goodsTypeId: [
          {
            required: true,
            message: '请选择类型',
            trigger: 'change'
          }
        ],
        name: [
          {
            required: true,
            message: '请填写货物名称',
            trigger: 'blur'
          }
        ],
        weight: [
          {
            required: true,
            message: '请填写重量',
            trigger: 'blur'
          }
        ]
      },
      goodsTypeList: [],
      unitList: [],
      searchGoodsTypeList: [],
      timeFrame: []
    }
  },
  created() {
    this.getGoodsTypeList()
  },
  methods: {
    getGoodsTypeList() {
      getGoodsTypeList().then((response) => {
        this.goodsTypeList = response
        this.searchGoodsTypeList = response
        this.getUnitList()
      })
    },
    getUnitList() {
      getUnitList().then((response) => {
        this.unitList = response
        this.getList()
      })
    },
    goodsTypeName(code) {
      const data = this.goodsTypeList.filter(item => item.code === code)
      return data.length > 0 ? data[0].name || '' : ''
    },
    goodsTypeId(name) {
      const data = this.goodsTypeList.filter((item) => item.name === name)
      return data.length > 0 ? data[0].code || '' : ''
    },

    unitName(id) {
      const data = this.unitList.filter(item => item.id === id)
      return data.length > 0 ? data[0].name || '' : ''
    },
    unitId(name) {
      const data = this.unitList.filter(item => item.name === name)
      return data.length > 0 ? data[0].id || '' : ''
    },
    getList() {
      this.listLoading = true
      if (this.listQuery.goodsTypeId !== undefined) {
        this.listQuery.goodsTypeIds.push(this.listQuery.goodsTypeId)
      }
      fetchCargoList(this.listQuery).then((response) => {
        console.log(response)
        this.list = response.records
        this.list.map((item, index) => {
          item.sort = index + 1
        })
        this.total = response.total
        this.listLoading = false
      })
    },
    // 搜索
    handleSearch() {
      this.listQuery.current = 1
      if (this.timeFrame.length > 1) {
        this.listQuery.operationStartTime = parseTime(this.timeFrame[0])
        this.listQuery.operationEndTime = parseTime(this.timeFrame[1])
      }
      this.getList()
    },
    sortChange(data) {},
    // 重置表单内容
    resetTemp() {
      this.temp = {
        id: undefined,
        goodsTypeId: '',
        name: '',
        weight: '',
        volume: undefined,
        quantity: undefined,
        unitId: undefined
      }
    },
    resetSearch() {
      this.listQuery = {
        current: 1,
        size: 20,
        name: undefined,
        goodsTypeId: undefined,
        goodsTypeIds: [],
        operationStartTime: undefined,
        operationEndTime: undefined
      }
    },
    // 新增弹窗
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 更新或者新增
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          console.log(this.temp)
          createCargo(this.temp).then((res) => {
            this.getList()
            this.dialogFormVisible = false
            const msg =
              this.dialogStatus === 'create' ? '添加成功' : '编辑成功'
            this.$notify({
              title: '成功',
              message: msg,
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 更新弹窗
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 处理删除选项
    handleDelete(row) {
      const arr = []
      arr.push(row.id)
      const data = {
        ids: arr
      }
      delCargo(data).then(() => {
        this.getList()
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.filter-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;

  .filter-item {
    margin-bottom: 0px;
  }

  .align-items {
    margin-bottom: 0;
  }

  .label {
    margin-right: 10px;
    margin-left: 10px;
  }
}

.dialog-footer {
  display: flex;
  align-items: center;
  justify-content: center;

  button {
    width: 100px;
  }
}

.content {
  margin-left: 0px;
  display: flex;

  .val {
    flex: 1;
  }

  .label {
    width: 30px;
    text-align: center;
  }
}
</style>
